import 'package:flutter/material.dart';
import 'package:puppy_store/models/home_model.dart';
import 'package:puppy_store/pages/home/widgets/loadingBg.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:puppy_store/widgets/custom_image.dart';

class CategoryGridsWidget extends StatefulWidget {
  const CategoryGridsWidget({this.categoryGrids, super.key});

  final List<CategoryGridsModel>? categoryGrids;

  @override
  State<CategoryGridsWidget> createState() => _CategoryGridsWidgetState();
}

class _CategoryGridsWidgetState extends State<CategoryGridsWidget> {
  double _imageWidth = 0;
  int _pages = 0;
  int _currentPage = 0;

  // 构建分类网格: 使用网格视图插件
  Widget _buildItem(List<CategoryGridsModel> categoryGrids) {
    return StaggeredGridView.countBuilder(
      crossAxisCount: 5,
      itemCount: categoryGrids.length,
      mainAxisSpacing: 16,
      physics: NeverScrollableScrollPhysics(), // 禁止滚动
      shrinkWrap: true, // shrinkWrap: true 表示子组件的大小是根据内容自适应的 搭配禁用滚动physics,
      itemBuilder: (context, index) {
        return Column(
          children: [
            Container(
              child: CustomImage(
                url: categoryGrids[index].picture!,
                width: _imageWidth,
                height: _imageWidth,
              ),
              // Image.network(
              //   categoryGrids[index].picture!,
              //   width: _imageWidth,
              //   height: _imageWidth,
              //   fit: BoxFit.cover,
              // ),
            ),
            Container(height: 20, child: Text(categoryGrids[index].name!)),
          ],
        );
      },
      staggeredTileBuilder: (index) => StaggeredTile.fit(1),
    );
  }

  List<Widget> _buildPages(List<CategoryGridsModel> categoryGrids) {
    List<Widget> items = [];
    // 计算分页总页数
    // (categoryGrids.length * 0.1).ceil() 分类的总个数14除以每页展示的分类10个数就是总页数
    _pages = (categoryGrids.length * 0.1).ceil();

    // 循环生成每个页面
    for (int i = 0; i < _pages; i++) {
      int start = i * 10;
      int end = (i + 1) * 10;
      if (end > categoryGrids.length) {
        // 如果 end 超过列表长度，截取到列表末尾
        items.add(_buildItem(categoryGrids.sublist(start)));
      } else {
        items.add(_buildItem(categoryGrids.sublist(start, end)));
      }
    }
    return items;
  }

  //是否是单行
  bool isSingleRow = false;

  // 根据总页数循环创建指示器元素
  List<Widget> _buildIndicator() {
    List<Widget> items = [];
    for (int i = 0; i < _pages; i++) {
      items.add(
        Container(
          height: 3,
          width: 30,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(1.5),
            color: _currentPage == i ? Colors.green : Colors.grey[300],
          ),
        ),
      );
    }
    return items;
  }

  @override
  Widget build(BuildContext context) {
    // 获取媒体查询
    double screenWidth = MediaQuery.of(context).size.width;
    // 计算分类图标的宽度: (屏幕宽度-6*16) * 0.2
    // (屏幕宽度-6*16) 5个图标的间距
    _imageWidth = (screenWidth - 6 * 16) * 0.2;

    // 分类行高, 不要放到build中去哦, 是不起作用的,
    double categorySingleRowHeight = 100;
    // 计算分类行高
    double categoryDoubleRowHeight = 2 * categorySingleRowHeight;

    // debugPrint('${widget.categoryGrids}');
    if (widget.categoryGrids != null) {
      return Container(
        color: Colors.white,
        child: Column(
          children: [
            // 分类网格
            AnimatedContainer(
              duration: Duration(milliseconds: 400),
              curve: Curves.ease,
              height:
                  isSingleRow
                      ? categorySingleRowHeight
                      : categoryDoubleRowHeight,
              color: Colors.white,
              child: Padding(
                padding: EdgeInsets.only(top: 10),
                child: PageView(
                  children: _buildPages(widget.categoryGrids!),
                  onPageChanged: (int index) {
                    int count =
                        widget.categoryGrids!
                            .sublist(index * 10, widget.categoryGrids!.length)
                            .length;
                    setState(() {
                      _currentPage = index;
                      isSingleRow = (count <= 5) ? true : false;
                    });
                  },
                ),
              ),
            ),
            // 指示器
            Padding(
              padding: EdgeInsets.only(top: 15, bottom: 10),
              child: Container(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  spacing: 2,
                  children: _buildIndicator(),
                ),
              ),
            ),
          ],
        ),
      );
    }
    // 实现骨架屏
    return StaggeredGridView.countBuilder(
      crossAxisCount: 5,
      itemCount: 10,
      mainAxisSpacing: 16,
      physics: NeverScrollableScrollPhysics(), // 禁止滚动
      shrinkWrap: true, // shrinkWrap: true 表示子组件的大小是根据内容自适应的 搭配禁用滚动physics,
      itemBuilder: (context, index) {
        return Column(
          children: [
            Container(
              decoration: BoxDecoration(
                color: Colors.grey[300],
                borderRadius: BorderRadius.circular(10),
              ),
              width: _imageWidth,
              height: _imageWidth,
            ),
            Padding(padding: EdgeInsets.only(top: 10)),
            Container(height: 20, width: _imageWidth, color: Colors.grey[300]),
          ],
        );
      },
      staggeredTileBuilder: (index) => StaggeredTile.fit(1),
    );
  }
}
